import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../http/api.dart';
import '../l10n/messages.dart';

class CargoInformation extends StatefulWidget {
  const CargoInformation({super.key, required this.goodsName, required this.packType, required this.Weight, required this.Volume, required this.chooseType});
  final String goodsName;
  final String packType;
  final String Weight;
  final String Volume;
  //1个人货源 2企业货源
  final int chooseType;
  @override
  State<CargoInformation> createState() => _CargoInformationState();
}

class _CargoInformationState extends State<CargoInformation> {

  List<String> tagList = ['吨包', '散装', '袋装', '托盘', '其他'];


  String goodsName="";
  String packagingType="";
  String goodsWeight="";
  String goodsVolume="";
  String parentDictValue="";
  int packIndex=-1;
  String goodsCount="";
@override
  void initState() {
    // TODO: implement initState
    super.initState();
     goodsName=widget.goodsName;
     packagingType=widget.packType;
     goodsWeight=widget.Weight;
    goodsVolume=widget.Volume;
    if(packagingType!="")
      packIndex=tagList.indexOf(packagingType);
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("货物信息",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: Column(
        children: [
        Expanded(child: ListView(
          children: [
            Container(
              margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
              padding: EdgeInsets.only(left: 20.w,top: 15.h,bottom: 15.h,right: 15.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              child: Column(
                children: [
                  GestureDetector(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(goodsName !=""?goodsName:"*请选择货物名称",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                        Icon(Icons.arrow_forward_ios,color: MyColors.hintColor,),
                      ],
                    ),
                    onTap: ()async{
                      final result = await  showModalBottomSheet(context: context, builder: (BuildContext context)
                      {
                        return chooseGoodsSheet();

                      });
                      if (result != null) {
                        setState(() {
                          goodsName =result[0];
                          parentDictValue=result[1];
                        });
                      }
                    },
                  ),
                  Divider(height: 20.h,color: MyColors.backgreyColor,),
                  Row(
                    children: [
                      Text("*",style: TextStyle(color: MyColors.themeColor,)),
                      Text("包装方式",style: TextStyle(color: Colors.black,fontSize: 14.sp),),

                    ],
                  ),
                  SizedBox(height: 8.h,),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Wrap(
                      spacing: 8.0, // 两个Container之间的水平间距
                      runSpacing: 8.0, // 行与行之间的垂直间距
                      children: tagList.asMap().entries.map((entry) {
                        int index = entry.key;
                        String tag = entry.value;

                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件，例如打印标签名称和索引
                            print('Tag $tag at index $index clicked');
                            setState(() {
                              packagingType=tag;
                              packIndex=index;
                            });

                          },
                          child: Container(
                            width: 60.0, // Container宽度
                            height: 30.0, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: packIndex == index ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor,  // Container的背景颜色为灰色
                              borderRadius: BorderRadius.circular(8.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                tag,
                                style: TextStyle(
                                  color: packIndex == index ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                    fontSize: 14.sp ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),


                ],
              ),
            ),

            Container(
              margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
              padding: EdgeInsets.only(left: 20.w,top: 15.h,bottom: 15.h,right: 15.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              child: Column(
                children: [
                  Row(
                    children: [
                      Text("*",style: TextStyle(color: MyColors.themeColor),),
                      Text("总重量/体积（至少填写一项）",style: TextStyle(color: Colors.black,fontSize: 14.sp)),
                    ],
                  ),
                  SizedBox(height: 10.h,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text("重量（吨）",style: TextStyle(color: Colors.black,fontSize: 14.sp)),
                      Container(
                        width: 200.w,
                        height: 30.h,
                        child:  Center(
                          child:  TextField(
                            decoration: InputDecoration(
                              hintText:  goodsWeight!=""?goodsWeight:'请输入货物重量',
                              hintStyle:goodsWeight!=""?TextStyle(fontSize: 14.sp,color: Colors.black):TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                              filled: true,
                              fillColor: MyColors.backgreyColor,
                              border: InputBorder.none,
                              alignLabelWithHint: true,
                              // contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal:8.0.h),
                            ),
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.left,
                            style: TextStyle(color: Colors.black),
                            onChanged: (value) {
                              setState(() {
                                print(value);
                                goodsWeight=value;
                              });
                            },
                          ),
                        ),


                      ),
                    ],
                  ),
                  SizedBox(height: 8.h,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text("体积（方）",style: TextStyle(color: Colors.black,fontSize: 14.sp)),
                      Container(
                        width: 200.w,
                        height: 30.h,
                        child:  Center(
                          child:  TextField(
                            decoration: InputDecoration(
                              hintText:  goodsVolume!=""?goodsVolume:'请输入货物体积',
                              hintStyle:goodsVolume!=""?TextStyle(fontSize: 14.sp,color: Colors.black):TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                              filled: true,
                              fillColor: MyColors.backgreyColor,
                              border: InputBorder.none,
                              alignLabelWithHint: true,
                              // contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal:8.0.h),
                            ),
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.left,
                            style: TextStyle(color: Colors.black),
                            onChanged: (value) {
                              setState(() {
                                print(value);
                                goodsVolume=value;
                              });
                            },
                          ),
                        ),


                      ),
                    ],
                  ),
                  if(widget.chooseType==2)
                    SizedBox(height: 8.h,),
                  if(widget.chooseType==2)
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text("数量（件）",style: TextStyle(color: Colors.black,fontSize: 14.sp)),
                      Container(
                        width: 200.w,
                        height: 30.h,
                        child:  Center(
                          child:  TextField(
                            decoration: InputDecoration(
                              hintText:  goodsCount!=""?goodsCount:'请输入货物数量',
                              hintStyle:goodsCount!=""?TextStyle(fontSize: 14.sp,color: Colors.black):TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                              filled: true,
                              fillColor: MyColors.backgreyColor,
                              border: InputBorder.none,
                              alignLabelWithHint: true,
                              // contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal:8.0.h),
                            ),
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.left,
                            style: TextStyle(color: Colors.black),
                            onChanged: (value) {
                              setState(() {
                                print(value);
                                goodsCount=value;
                              });
                            },
                          ),
                        ),


                      ),
                    ],
                  )
                ],
              ),
            ),
          ],
        ),
        ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 40.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(
                      
                        color:goodsName!=""&&packagingType!=""&&(goodsWeight!=""||goodsVolume!="")? Color.fromRGBO(231, 112, 27, 0.85):Color.fromRGBO(223, 223, 223, 1),
                        borderRadius: BorderRadius.all(Radius.circular(30))),

                    width: double.infinity,


                    child: TextButton(
                      child: Text("确定",style: TextStyle(color: Colors.white,fontSize: 16.sp,fontWeight: FontWeight.w600),),

                      onPressed: (){
                        if (goodsVolume!=""&&goodsWeight!="") {
                          Navigator.pop(context, [
                            "$goodsName,$packagingType,$goodsWeight吨,$goodsVolume方",
                            goodsName,
                            packagingType,
                            goodsWeight,
                            goodsVolume,
                            parentDictValue,
                            goodsCount,
                          ],);
                        }else if(goodsVolume==""&&goodsWeight!=""){
                          Navigator.pop(context, [
                            "$goodsName,$packagingType,$goodsWeight吨",
                            goodsName,
                            packagingType,
                            goodsWeight,
                            goodsVolume,
                            parentDictValue,
                            goodsCount,
                          ],);
                        }else if(goodsVolume!=""&&goodsWeight==""){
                          Navigator.pop(context, [
                            "$goodsName,$packagingType,$goodsVolume",
                            goodsName,
                            packagingType,
                            goodsWeight,
                            goodsVolume,
                            parentDictValue,
                            goodsCount,
                          ],);
                        }
                      },
                    )
                ),
              ],
            ),
          ),
        ],
      ),


    );
  }
}

class chooseGoodsSheet extends StatefulWidget {
  const chooseGoodsSheet({super.key});

  @override
  State<chooseGoodsSheet> createState() => _chooseGoodsSheetState();
}

class _chooseGoodsSheetState extends State<chooseGoodsSheet> {


  List dataList=[];
  List<String> goodsList = [];
  String goodsName="";
  String writeStr="";


  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ///initState 中添加监听，记得销毁
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    getHisGoods();
  }
  void getHisGoods()async{
    List<String>? hisGoods = await HisGoodsNameManager.getGoodsName();
    if (hisGoods != null) {
      setState(() {
        goodsList=hisGoods;
        goodsList=goodsList.toSet().toList();
        print("hisLsit:${goodsList}") ;

      });
    } else {
      // 处理未找到存储的地址列表的情况
      print('No addresses found');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      padding: EdgeInsets.only(left: 20.w,top: 15.h,right: 15.w),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp)),
                onTap: (){
                  Navigator.pop(context);
                },
              ),
              Text("货物名称",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              GestureDetector(
                child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp)),
                onTap: (){
                  Navigator.pop(context,[writeStr,"1700"]);
                },
              ),
            ],
          ),
          SizedBox(height: 20.h,),
          Container(
            height: 50.h,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(10)),

            ),
            child:  BrnSearchText(
              focusNode: focusNode,
              controller: textController,
              searchController: scontroller..isActionShow = false,
              innerColor:MyColors.backgreyColor,
              borderRadius:BorderRadius.all(const Radius.circular(10.0)),
              hintText:"请如实规范填写货物名称",
              onTextClear: () {
                debugPrint('sss');
                setState(() {
                  dataList =[];
                });
                return false;
              },
              autoFocus: true,
              onActionTap: () {
                scontroller.isClearShow = false;
                scontroller.isActionShow = false;
                focusNode.unfocus();
                // BrnToast.show('取消', context);
                setState(() {
                  dataList =[];
                });
              },
              onTextCommit: (text) {
                BrnToast.show('提交内容 : $text', context);
              },
              onTextChange: (text) {
                dio.interceptors.add(InterceptorsWrapper(
                    onRequest: (options, handler) async {
                      options.headers["satoken"] =  await TokenManager.getToken();
                      return handler.next(options);
                    }
                ));

                dio.get<String>(MyServiceUrl.header+'api/system/dev/dict/cargo/list?key=$text')
                    .then((r) {
                  setState(() {
                    print(r);
                    Map<String, dynamic> jsonMap = json.decode(r.toString());

                    // 获取code和data
                    String code = jsonMap['code'].toString();
                    if (code == "200") {
                      dataList = jsonMap['data'];
                      print(dataList);
                    } else {}
                    // 打印结果
                    print('Code: $code');
                  });
                }).catchError((error) {
                  print(error);
                });
                writeStr =text;
                // BrnToast.show('输入内容 : $text', context);
              },
            ),
          ),
          dataList.length>0?
          Container(
            height: 240.h,
            color: Colors.white,
              padding: EdgeInsets.only(top: 8.h),
              child: ListView.builder(
              itemCount: dataList.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  padding: EdgeInsets.only(left: 8.w,right: 8.w),
                child: Column(
                  children: [
                    GestureDetector(
                      child:Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(child:  Row(
                            children: [
                              Text(dataList[index]['cargoName'],style: TextStyle(color:Colors.black,fontSize: 14.sp),),
                            ],
                          ),),


                        ],
                      ),
                      onTap: ()async{
                        await HisGoodsNameManager.saveGoodsName(goodsList);
                        setState(() {
                          goodsList.add(dataList[index]['cargoName']);
                          goodsName =dataList[index]['cargoName'];
                          Navigator.pop(context,[goodsName,dataList[index]['cargoTypeCode']]);
                        });
                      },
                    ),

                    Divider(height: 16.h,color: MyColors.backgreyColor,),
                  ],
                ),
                );
              }
              ),

          ):
          Column(
            children: [
              SizedBox(height: 10.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("历史搜索",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600),),
                  GestureDetector(
                    child:Image.asset("lib/Images/OrderList/货物名称垃圾桶icon.png",width: 20.w,height: 20.h,),
                    onTap: (){
                       HisGoodsNameManager.clearGoodsName();
                       setState(() {
                         goodsList=[];
                       });
                    },
                  ),
                ],
              ),
              SizedBox(height: 8.h,),
              BrnSelectTag(
                  tags: goodsList,
                  spacing: 8.w,
                  tagWidth:50.w,
                  tagHeight:30.h,
                  initTagState: [false],
                  alignment:Alignment.centerLeft,
                  selectedTagBackgroundColor:Color(0XFFFBECE4),
                  selectedTagTextStyle:TextStyle(color: MyColors.themeColor,fontSize: 14.sp),
                  tagTextStyle:TextStyle(fontSize: 14.sp),
                  onSelect: (selectedIndexes) {
                    String getselected=selectedIndexes.toString();
                    String result = getselected.substring(1, getselected.length - 1);
                    int? index = int.tryParse(result);
                    setState(() {
                      if (index !=null)goodsName=goodsList[index];
                      Navigator.pop(context,[goodsName,"1700"]);
                    });


                  }) ,
              SizedBox(height: 20.h,),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("*",style: TextStyle(color: MyColors.themeColor),),
                  Container(
                    width: 300.w,
                    child:   BrnExpandableText(
                        text: '请勿发布及托运危险货物、违禁货物，限运货物需有相应证明文件，否则您可能面临平台禁用账号、行政处罚、国家公诉等不利后果。具体详见法律公告页:《关于速配货平台货物发布及承运规范的公告》',
                        maxLines: 1,
                        onExpanded:(bool isExpanded) {
                          if (isExpanded) {
                            debugPrint('已经展开');
                          }
                          else {
                            debugPrint('已经收起');
                          }
                        }
                    ),
                  ),
                ],
              ),
            ],
          ),

        ],
      ),
    );
  }
}
